#include "ServerApp.h"
#include "ClientSessionManager.h"
#include "RedisManager.h"
#include "PlayerManager.h"
#include "ClientSession.h"
#include "ScriptManager.h"


ServerApp::ServerApp()
{
	m_pThreadHandleTask = NULL;
	m_bIsRun = true;
}

int ServerApp::Init()
{
	ClientSessionManager::getInstance().Init();
	RedisManager::getInstance().Init();
	PlayerManager::getInstance();

	ScriptManager::getInstance().Init(0);

	return 0;
}

int ServerApp::Run()
{
	ClientSessionManager &clientSessionManager = ClientSessionManager::getInstance();
	clientSessionManager.Run();

	m_pThreadHandleTask = new boost::thread(boost::bind(&ServerApp::ThreadFunc, this));

	clientSessionManager.Join();
	Join();

	return 0;
}

void ServerApp::Join()
{
	m_pThreadHandleTask->join();
}

int ServerApp::Shutdown()
{
	m_bIsRun = false;
	return 0;
}

void ServerApp::ExecuteTask()
{
	while(m_bIsRun)
	{
		try
		{
			ClientSessionManager::getInstance().HandleMessage();
		}
		catch (std::exception &e)
		{
			LERROR << e.what();
		}
		catch (...)
		{
			LERROR << "unknown exception";
		}
	}

}

void ServerApp::ThreadFunc(ServerApp *pServerApp)
{
	pServerApp->ExecuteTask();
}

